﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.UI.MobileControls;
using System.Collections.Generic;

namespace YXShop.Web.membercenter.order
{
    public partial class order_hadpay : System.Web.UI.Page
    {
        private decimal outPrice = 0;
        YXShop.BLL.Order.Orders orderBll = new YXShop.BLL.Order.Orders();
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                InitWebControl();
                string orderId = ChangeHope.WebPage.PageRequest.GetQueryString("id");
                if(orderId!=null&&orderId!="")
                {
                    this.HyperLink3.NavigateUrl = "order_info.aspx?OrderId=" + orderId;
                    ViewState["orderId"] = orderId;
                    BindOrderInfo(orderId);
                }
            }
        }

        #region 验证
        private void InitWebControl()
        {
            ChangeHope.WebPage.WebControl.SetDate(this.txtData);
            ChangeHope.WebPage.WebControl.Validate(this.txtRemitMoney,"汇款金额必须是数字","isint","必填","该项为必填项");
            this.Form.Attributes.Add("onsubmit", "return CheckForm()");
            BindBank();
        }
        #endregion

        #region 计算商品总价
        private double TotalPrice(string orderId)
        {
            YXShop.BLL.Order.OrderProduct bll = new YXShop.BLL.Order.OrderProduct();
            DataTable dt = bll.GetListOrderProduct(orderId);
            double totalPrice = 0;
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    totalPrice += Convert.ToDouble(dt.Rows[i]["ProPrice"].ToString()) * Convert.ToDouble(dt.Rows[i]["ProNum"].ToString());
                }
            }
            return totalPrice;
        }
        #endregion

        #region 绑定
        private void BindBank()
        {
            YXShop.BLL.SystemInfo.BankInfo bll = new YXShop.BLL.SystemInfo.BankInfo();
            List<YXShop.Model.SystemInfo.BankInfo> bankList = bll.GetAll();
            if(bankList!=null)
            {
                this.DdlBank.DataSource = bankList;
                this.DdlBank.DataValueField = "ID";
                this.DdlBank.DataTextField = "BankName";
                this.DdlBank.DataBind();
            }
        }
        #endregion

        #region 初始信息
        private void BindOrderInfo(string orderId)
        {          
            YXShop.Model.Order.Orders order = orderBll.GetModel(Convert.ToInt32(orderId));
            if(order!=null)
            {
                ViewState["FactPrice"] = order.FactPrice.ToString();
                this.lblClientName.Text = order.ConsigneeName.ToString();
                this.myuser.Text = order.UserId.ToString();
                this.lblNumber.Text = order.OrderId.ToString();
                this.lblMoney.Text = (TotalPrice(order.Id.ToString()) + Convert.ToDouble(order.Courier)).ToString("f4");
                this.lblEndPayment.Text = Endpayment(order.OrderId.ToString());
                if (Convert.ToDecimal(order.FactPrice) <= Convert.ToDecimal(Endpayment(order.OrderId.ToString())))
                {
                    //查看是否已经付清
                    ChangeHope.WebPage.Script.AlertAndGoBack("该订单已经支付清");
                }else
                {
                    this.txtRemitMoney.Text = (Convert.ToDecimal((TotalPrice(order.Id.ToString()) + Convert.ToDouble(order.Courier)).ToString("f4")) - Convert.ToDecimal(Endpayment(order.OrderId.ToString()))).ToString();
                }
            }
        }
        #endregion

        #region 已付款
        public string Endpayment(string orderId)
        {
            string totle = string.Empty;
            decimal remPrice = 0;
            decimal payPrice = 0;
            decimal prePrice = 0;
            //银行支付
            YXShop.BLL.Order.RemittanceInfo remBll = new YXShop.BLL.Order.RemittanceInfo();
            List<YXShop.Model.Order.RemittanceInfo> remdate = remBll.GetAll("orderid='" + orderId + "'");
            if (remdate.Count > 0)
            {
                foreach (YXShop.Model.Order.RemittanceInfo da in remdate)
                {
                    remPrice += Convert.ToDecimal(da.RemittanceMoney.ToString());
                }
            }
            //现金支付
            YXShop.BLL.Order.PaymentMoney payBll = new YXShop.BLL.Order.PaymentMoney();
            List<YXShop.Model.Order.PaymentMoney> paydata = payBll.GetAll("orderid='" + orderId + "'");
            if (paydata.Count > 0)
            {
                foreach (YXShop.Model.Order.PaymentMoney da in paydata)
                {
                    payPrice += Convert.ToDecimal(da.GatheringMoney.ToString());
                }
            }
            //预付款
            YXShop.BLL.Order.PrepayMoney preBll = new YXShop.BLL.Order.PrepayMoney();
            List<YXShop.Model.Order.PrepayMoney> predata = preBll.GetAll("orderid='" + orderId + "'");
            if (predata.Count > 0)
            {
                foreach (YXShop.Model.Order.PrepayMoney da in predata)
                {
                    prePrice += Convert.ToDecimal(da.PayoutMoney);
                }
            }
            totle = (remPrice + payPrice + prePrice).ToString();
            return totle;
        }
        #endregion

        protected void linkSave_Click(object sender, EventArgs e)
        {
            YXShop.BLL.Order.RemittanceInfo remitBll = new YXShop.BLL.Order.RemittanceInfo();
            YXShop.BLL.Member.UserinAndExp bankBll = new YXShop.BLL.Member.UserinAndExp();
            YXShop.BLL.Member.MemberAccount memberBll = new YXShop.BLL.Member.MemberAccount();
            YXShop.Model.Member.MemberAccount member=memberBll.GetModel(Convert.ToInt32(Session["MemberID"]));
            YXShop.Model.Order.RemittanceInfo remit = new YXShop.Model.Order.RemittanceInfo();
            YXShop.Model.Member.UserinAndExp bank = new YXShop.Model.Member.UserinAndExp();
            YXShop.Model.Order.Orders orderModel = orderBll.GetModel(Convert.ToInt32(ViewState["orderId"].ToString()));
            if(member!=null)
            {    
                if(Convert.ToDecimal(this.txtRemitMoney.Text)<=0)
                {
                    this.ltlMsg.Text = "操作失败!汇款的资金不能少于0，请填写正确";
                    this.pnlMsg.Visible = true;
                    this.pnlMsg.CssClass = "actionErr";
                    return;
                }
                if (Convert.ToDecimal(member.Capital) > Convert.ToDecimal(this.txtRemitMoney.Text))
                {   
                    //订单汇款记录
                    remit.OrderId = this.lblNumber.Text.ToString();
                    remit.UserName = this.myuser.Text.ToString();
                    remit.RemittanceDate = Convert.ToDateTime(this.txtData.Text);
                    //如果输入金额大于剩余要付金额就取剩余金额（因为如果输入资金多了会自动转到会员帐户上）
                    remit.RemittanceMoney = 0;
                    remit.RemintanceBank = Convert.ToInt32(this.DdlBank.SelectedValue);
                    remit.PresentTicket = 0;
                    remit.Remark =Session["MemberName"].ToString()+"用户汇入款："+this.txtRemitMoney.Text+"元,请查收"+ this.txtRemark.Text.ToString();
                    remit.InformMode = this.chbInform.Checked ? this.chbInform.Text : "无";
                    remit.NoteDate = Convert.ToDateTime(System.DateTime.Now);
                    remit.NoteName = Session["MemberName"].ToString();

                    //用户银行汇款记录
                    bank.UserId = Session["MemberName"].ToString();
                    bank.UID = Convert.ToInt32(Session["MemberID"].ToString());
                    //同上
                    bank.AdsumMoney = Convert.ToDecimal(this.txtRemitMoney.Text) > (Convert.ToDecimal(orderModel.FactPrice) - Convert.ToDecimal(this.lblEndPayment.Text)) ? Convert.ToDecimal(orderModel.FactPrice) - Convert.ToDecimal(this.lblEndPayment.Text) : Convert.ToDecimal(this.txtRemitMoney.Text);
                    bank.AdsumMoneyDate = Convert.ToDateTime(this.txtData.Text);
                    bank.PresentCoupons = 0;
                    bank.RemitMode = 1;
                    bank.RemitBank = this.DdlBank.SelectedItem.Text;
                    bank.Remark=this.txtRemark.Text.Trim()==string.Empty ? "我已汇款："+this.txtRemitMoney.Text+",订单号为："+ViewState["orderId"].ToString():this.txtRemark.Text.Trim();
                    bank.FormMode = this.chbInform.Checked ? this.chbInform.Text : "无";
                    bank.BosomNote = "用户订单汇款";
                    bank.NoteDate = Convert.ToDateTime(System.DateTime.Now);
                    bank.NoteName = Session["MemberName"].ToString();
                    bank.InComeandExpState = 1;
                    bank.State = 1;
                 
                    try
                    {                     
                        int count=0;
                        count = remitBll.Add(remit); //订单汇款记录
                        if(count>0)
                        {
                           bankBll.Add(bank);    //银行记录
                           
                           //总付款
                           this.ltlMsg.Text = "添加银行支付信息成功!";
                           this.pnlMsg.Visible = true;
                           this.pnlMsg.CssClass = "actionOk";
                        }
                    }
                    catch (Exception exe)
                    {
                        Response.Write(exe.Message);
                    }
                    
                }
                else
                {
                    this.ltlMsg.Text = "操作失败!您的资金少于付款金额，请充值";
                    this.pnlMsg.Visible = true;
                    this.pnlMsg.CssClass = "actionErr";
                    return;
                }
            }

        }
    }
}
